<?php
header('Content-Type:text/html; charset=utf-8;');
ini_set('max_execution_time', '0');
if(!defined('DS'))define('DS', DIRECTORY_SEPARATOR);
if(!defined('ROOTPATH'))define('ROOTPATH', __DIR__.DS);
if(!defined('ZIPPATH'))define('ZIPPATH', ROOTPATH.'zip'.DS);
chmod(ZIPPATH,'775');
$data = $_POST;
file_put_contents('data.json','var _data = '.json_encode($data));
$_xml_data = $data;
unset($_xml_data['src_path']);
$_xml_data['xz_log'] = explode("\n",trim($_xml_data['xz_log']));
$_xml_data['xz_files'] = gitlogprase($_xml_data['xz_files']);

mzip($data,$_xml_data);

exit(json_encode(['file'=>ZIPPATH.$data['xz_branch'].'_'.$data['xz_realse'].'_'.$data['xz_version'].".zip"]));


/**
 * 数组转XML
 * @param array $arr
 * @param boolean $htmlon
 * @param boolean $isnormal
 * @param intval $level
 * @return type
 */
function array2xml($arr, $htmlon = TRUE, $isnormal = FALSE, $level = 1) {
    $s = $level == 1 ? "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<root>\r\n" : '';
    $space = str_repeat("\t", $level);
    foreach($arr as $k => $v) {
        if(!is_array($v)) {
            $s .= $space."<item id=\"$k\">".($htmlon ? '<![CDATA[' : '').$v.($htmlon ? ']]>' : '')."</item>\r\n";
        } else {
            $s .= $space."<item id=\"$k\">\r\n".array2xml($v, $htmlon, $isnormal, $level + 1).$space."</item>\r\n";
        }
    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
    return $level == 1 ? $s."</root>" : $s;
}

/**
 *GIT日志分组
 */
function gitlogprase($str){
	$rs = [];
	$_data = explode("\n",trim($str));
	foreach($_data as $k=>$v){
		$_arr = explode("\t",$v);
		if($_arr[2] == '已添加') $rs['A'][] = $_arr[0];
		if($_arr[2] == '已修改') $rs['U'][] = $_arr[0];
		if($_arr[2] == '已删除') $rs['D'][] = $_arr[0];
	}
	return $rs;
}

function mzip($data,$_xml_data){
	//var_dump($data['src_path']);
	$filename = $data['xz_branch'].'_'.$data['xz_realse'].'_'.$data['xz_version'].".zip";
	// 生成文件
	$zip = new \ZipArchive ();
	
	// 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
	if ($zip->open (ZIPPATH.$filename ,\ZipArchive::OVERWRITE) !== true) {
		//OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
		if($zip->open (ZIPPATH.$filename ,\ZipArchive::CREATE) !== true){
			// 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
			exit ( '无法打开文件，或者文件创建失败' );
		}
	}
	//添加到压缩包
	$zip -> addFromString ( 'upgrade.xml' ,  array2xml($_xml_data) );
	addFileToZip($data['xz_realse']=='install' ? 'src'.DS.'install':'src'.DS.'upgrade',$zip);
	// 关闭
	$zip->close ();
}

/*压缩多级目录 
    $openFile:目录句柄 
    $zipObj:Zip对象 
    $sourceAbso:源文件夹路径 
*/
function addFileToZip($path,$zip){
	if(!defined('_SRCDIR_'))define('_SRCDIR_', $path.DS);
	$handler=opendir($path); //打开当前文件夹由$path指定。
	while(($filename=readdir($handler))!==false){
	  if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..'，不要对他们进行操作
		if(is_dir($path.DS.$filename)){// 如果读取的某个对象是文件夹，则递归
		  addFileToZip($path.DS.$filename, $zip);
		}else{ //将文件加入zip对象
			$_dst_filename = $path.DS.$filename;
		  $zip->addFile($path.DS.$filename,str_replace(_SRCDIR_,'',$_dst_filename));
		}
	  }
	}
	@closedir($path);
  }
